package com.atguigu.java;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionTest {
    @Test
    public void test() throws ClassNotFoundException {
        Class c1 = Person.class;
        System.out.println(c1);
        Person p1 = new Person();
        Class c2 = p1.getClass();
        System.out.println(c2);
        Class c3 = Class.forName("com.atguigu.java.Person");
        System.out.println(c3);
        System.out.println(c1 == c2);
        System.out.println(c1 == c3);
        ClassLoader classLoader = ReflectionTest.class.getClassLoader();
        Class c4 = classLoader.loadClass("com.atguigu.java.Person");
        System.out.println(c4);
        System.out.println(c1 == c4);
    }
    @Test
    public void test1() throws IllegalAccessException, InstantiationException {
        Class clazz = Person.class;
        Object o = clazz.newInstance();
        System.out.println(o);

    }
    @Test
    public void test2() throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class clazz = Person.class;
        Person p = (Person) clazz.newInstance();
        Field name = clazz.getDeclaredField("name");
        Field age = clazz.getDeclaredField("age");
        name.setAccessible(true);
        age.setAccessible(true);
        age.set(p,11);
        name.set(p,"jan");
        System.out.println(age.get(p));
        System.out.println(name.get(p));
    }
    @Test
    public void test3() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class clazz = Person.class;
        Person p = (Person) clazz.newInstance();
        Method showNation = clazz.getDeclaredMethod("showNation", String.class);
        showNation.setAccessible(true);
        Object china = showNation.invoke(p, "china");
        System.out.println(china);
        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        Object invoke = showDesc.invoke(Person.class);
        System.out.println(invoke);



    }
    @Test
    public void test4() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Person.class;
        Constructor con = clazz.getDeclaredConstructor(String.class);
        con.setAccessible(true);
        Person tom = (Person) con.newInstance("tom");
        System.out.println(tom);
    }
}
